import { messages } from 'share/common';
import React, { Component } from 'react';
import 'styles/expense/expense-util.scss';
import { Switch, Tooltip } from 'antd';
import { getAttachment }  from 'containers/expense/util';
import ExpenseAdjunctService from './expense-adjunct-service';
import financeAuditService from '../../financial-management/new-finance-audit/finance-audit.service';

class Util extends Component {

  static contextTypes = {
    currentExpense: React.PropTypes.object,
    isWaitForAudit: React.PropTypes.bool
  };

  constructor(props) {
    super(props);
    this.state = {
      checkLoading: false,
      currentAttachment: this.props.currentAttachment,
      ...ExpenseAdjunctService.utils()
    };
  }

  handleUtil = (flag) => {
    const { attachmentUtils } = this.state;
    if (flag === 'zoom-in') {
      attachmentUtils.forEach(item => item.type === flag && (item.type = 'zoom-out', item.name = messages('expense-1.key688')/*缩小*/));
    }

    if (flag === 'zoom-out') {
      attachmentUtils.forEach(item => item.type === flag && (item.type = 'zoom-in', item.name = messages('expense-1.key678')/*放大*/));
    }
    this.setState({ attachmentUtils });
    this.props.handleUtil(flag);
  };

  handleCheck = async () => {
    this.setState({ checkLoading: true });
    const { currentAttachment, currentAttachment: { attachmentOID }, attachmentChecklist } = this.props;
    const { currentExpense: { invoiceOID } } = this.context;
    await financeAuditService.checkAttachment({
      attachmentOID,
      checked: !attachmentChecklist[currentAttachment.id],
      invoiceOID,
    });
    this.setState({ checkLoading: false });
    this.props.onChange({ isChecked: true, checked: !attachmentChecklist[currentAttachment.id] });
  };

  handleDisabled = (flag) => {
    const { currentFlag, currentAttachmentIndex, mergeAdjuncts } = this.props;

    if (!mergeAdjuncts[0]) {
      return false;
    }

    if (flag === 'left') {
      return currentAttachmentIndex === 0 && currentFlag === mergeAdjuncts[0].type;
    }

    if (flag === 'right') {
      return currentAttachmentIndex === mergeAdjuncts[mergeAdjuncts.length - 1].body.length - 1 && currentFlag === mergeAdjuncts[mergeAdjuncts.length - 1].type;
    }

  };

  handleChangeAttachment = (flag) => {
    let { currentAttachmentIndex, currentFlag, mergeAdjuncts } = this.props, adjunctIndex = mergeAdjuncts.findIndex(item => item.type === currentFlag);

    if (flag === 'left') {
      if (currentAttachmentIndex === 0 && adjunctIndex === 0) {
        return;
      }
      if (currentAttachmentIndex !== 0) {
        currentAttachmentIndex--;
      } else {
        adjunctIndex--;
        currentFlag = mergeAdjuncts[adjunctIndex].type;
        currentAttachmentIndex = mergeAdjuncts[adjunctIndex].body.length - 1;
      }
    }

    if (flag === 'right') {
      if (adjunctIndex === mergeAdjuncts.length - 1 && currentAttachmentIndex === mergeAdjuncts[adjunctIndex].body.length - 1) {
        return;
      }
      if (currentAttachmentIndex !== mergeAdjuncts[adjunctIndex].body.length - 1) {
        currentAttachmentIndex++;
      } else {
        adjunctIndex++;
        currentAttachmentIndex = 0;
        currentFlag = mergeAdjuncts[adjunctIndex].type;
      }
    }

    const currentAdjunct = mergeAdjuncts[adjunctIndex].body[currentAttachmentIndex];
    const currentAttachment = getAttachment(currentAdjunct);
    this.props.onChange({ currentAttachment, currentAttachmentIndex, currentFlag, currentAdjunct });
  };


  handleChangeTabs = (currentFlag, index) => {
    const { mergeAdjuncts } = this.props;
    this.props.onChange({
      currentFlag,
      currentAttachmentIndex: 0,
      currentAttachment: getAttachment(mergeAdjuncts[index].body[0]),
      currentAdjunct: mergeAdjuncts[index].body[0]
    });
  };

  handleLabels = (type) => {
    const { labelFilter } = this.props;
    const index = labelFilter.findIndex(label => label === type);
    !~index ? labelFilter.push(type) : labelFilter.splice(index, 1);
    this.props.onChange({ labelFilter, isRestData: true });
  };

  //附件是否为图片
  isImage = (file) => {
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    return imageExtension.has(this.getExtension(file));
  };


  getExtension = file => {
    let fileName = file.fileName || file.name || (file.response ? (file.response.fileName || file.response.name || '') : '');
    if (!fileName) {
      return '';
    }
    let sections = fileName.split('.');
    let extension = sections[sections.length - 1].toLowerCase();
    return extension.length > 3 ? extension.substring(0, 4) : extension;
  };

  renderAttachmentUtil = (item) => {
    let { currentAttachment = {}, attachmentChecklist = {} } = this.props, { checkLoading, components } = this.state;
    const { isWaitForAudit } = this.context;
    if (item.type === 'check') {
      return (
        isWaitForAudit &&
        <Tooltip title={item.name} key={item.type}>
          <Switch
            loading={checkLoading}
            size="small"
            checked={attachmentChecklist[currentAttachment.id]}
            onClick={() => this.handleCheck()}
            className="util-audit util-attachment-child"
          />
        </Tooltip>
      );
    }

    if (item.type === 'line') {
      return (<div className="util-attachment-child line">|</div>);
    }

    return (
      <Tooltip title={item.name} key={item.type} onClick={() => this.handleUtil(item.type)}>
        <div className="util-icon util-attachment-child ">
          {
            React.createElement(components[item.type])
          }
        </div>
      </Tooltip>
    );
  };


  renderLabels() {
    const { receiptLabels = [], labelFilter = [] } = this.props;
    return (
      <div className="util-labels">
        {
          receiptLabels.map(item => <span
            className={`util-label ${labelFilter.includes(item.type) && 'util-label-selected'}`}
            onClick={() => this.handleLabels(item.type)}>{item.name}</span>)
        }
      </div>
    );
  }

  renderContent = () => {
    const { gestures } = this.state;
    const { mergeAdjuncts, currentFlag, currentAttachmentIndex } = this.props;
    const jsx_map = gestures
      .map(item => React.createElement('div',
        {
          disabled: this.handleDisabled(item.type),
          className: 'util-icon util-kinds-child',
          onClick: () => this.handleChangeAttachment(item.type)
        },
        React.createElement(item.component)));

    jsx_map.splice(1, 0,
      ...(mergeAdjuncts
          .map((item, index) => {
            const { length } = item.body;
            return (
              <div
                onClick={() => this.handleChangeTabs(item.type, index)}
                key={item.type}
                className={`util-kinds-text util-kinds-child ${currentFlag === item.type ? 'util-kinds-text-line' : ''}`}
              >
                {item.name}:{currentFlag === item.type ? `${currentAttachmentIndex + 1}/${length}` : length}
              </div>
            );
          })
      ));
    return jsx_map;
  };


  render() {
    const { isListMode, attachmentUtils } = this.state;
    const { currentAttachment = {}, receiptLabels, style } = this.props;
    let utils_map;
    return (
      <section className="util" style={style}>
        <div className={`util-header ${isListMode && 'util-list-mode'}`}>
          <div className="util-kinds">
            {this.renderContent()}
          </div>
          <div className="util-attachment">
            {attachmentUtils.filter(item => {
              if (this.isImage(currentAttachment)) {
                return true;
              } else if (!currentAttachment.attachmentOID) {
                utils_map = ['list'];
              } else {
                utils_map = ['line', 'check', 'list', 'download'];
              }
              return utils_map.includes(item.type);
            })
              .map(item => this.renderAttachmentUtil(item))}
          </div>
        </div>
        {receiptLabels && receiptLabels[0] && this.renderLabels()}
      </section>
    );
  }
}

Util.propTypes = {
  changeCurrentFlag: React.PropTypes.func,
  attachmentChecklist: React.PropTypes.object,
};

Util.defaultPropTypes = {
  attachmentChecklist: {}
};

export default Util;
